package club.menglinking.wechat.controller.adminController;

import club.menglinking.wechat.entity.Json;
import club.menglinking.wechat.util.BaseUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LogManagerController
 * @Author xuan
 * @Date 19-1-7 下午9:08
 * @Version 1.0
 * @Description
 **/
@RestController
@Slf4j
public class LogManagerController {

    @Value("${logging.file}")
    private String logFilePath;

    @Value("${logging.file.max-size}")
    private String maxSize;

    ObjectMapper mapper=new ObjectMapper();

    @GetMapping("/log")
    public void downloadLog(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("有下载日志文件请求进来---IP地址:" + BaseUtil.getBaseUtil().getIpAddress(request));
        response.setHeader("Content-Disposition", "attachment;fileName=systemLog" + BaseUtil.getBaseUtil().getIntegerTime() + ".log");
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");
        InputStream ins = null;
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            ins = new FileInputStream(logFilePath);
            int len = 0;
            byte buf[] = new byte[1024];
            while ((len = ins.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            ins.close();
        }

    }

    @GetMapping("/logSize")
    public String getLogSize(HttpServletRequest request) throws JsonProcessingException {
        log.info("有查看日志大小的请求进来---IP地址:" + BaseUtil.getBaseUtil().getIpAddress(request));
        Json json = new Json();
        File file = new File(logFilePath);
        if (file.exists()&&file.isFile()){
            log.info("文件存在，已找到该文件");
            String fileSize = (int) (file.length() / 1024 + 1)+"";
            Map<String,String> parm=new HashMap<>();
            parm.put("fileSize",fileSize+"KB");
            parm.put("maxSize",maxSize);
            json.setStatus(200);
            json.setData(parm);
            json.setMsg("file is exists");
        }else {
            log.info("文件不存在,或者不是一个文件");
            json.setStatus(400);
            json.setMsg("file is not exists");
        }
        return mapper.writeValueAsString(json);
    }


}
